#include "LapList.hpp"
#include "Clock.hpp"
#include "AssetManager.hpp"
#include "Notification.hpp"
#include "Util.hpp"
#include <cpp3ds/System/I18n.hpp>
#include <cpp3ds/System/FileSystem.hpp>
#include <TweenEngine/Tween.h>
#include <time.h>
#include <stdlib.h>

namespace Clock {

LapList::LapList()
: m_scrollPos(0.f)
{
	m_textEmptyList.setString("The lap list is empty.\nPress the X button to add one.");
	m_textEmptyList.setCharacterSize(10);
	m_textEmptyList.useSystemFont();
	m_textEmptyList.setPosition(240.f, 120.f);
	m_textEmptyList.setFillColor(cpp3ds::Color(66, 66, 66));
	m_textEmptyList.setOrigin(m_textEmptyList.getLocalBounds().width / 2, m_textEmptyList.getLocalBounds().height / 2);
}

LapList::~LapList()
{

}

void LapList::draw(cpp3ds::RenderTarget &target, cpp3ds::RenderStates states) const
{
	states.transform *= getTransform();
	states.scissor = cpp3ds::UintRect(0, 35, 320, 205);

	target.draw(m_textEmptyList, states);

	for (auto& item : m_lapItems) {
		float posY = item->getPosition().y;
		if (posY > -10.f && posY < 240.f)
			target.draw(*item, states);
	}
}

void LapList::update(float delta)
{
	m_tweenManager.update(delta);
}

void LapList::processEvent(const cpp3ds::Event& event)
{

}

void LapList::setScroll(float position)
{
	m_scrollPos = std::round(position);
	repositionItems(true);
}

float LapList::getScroll()
{
	return m_scrollPos;
}

void LapList::repositionItems(bool noAnim)
{
	float posY = 36.f + m_scrollPos;
	for (auto& item : m_lapItems)
	{
		item->setPosition(160.f, item->getPosition().y);
		TweenEngine::Tween::to(*item, util3ds::TweenSprite::POSITION_Y, noAnim ? 0.f : 0.2f)
			.target(posY)
			.start(m_tweenManager);
		posY += item->getHeight();
	}
	m_size.y = posY - 6.f - m_scrollPos;
	updateScrollSize();
}

const cpp3ds::Vector2f &LapList::getScrollSize()
{
	return m_size;
}

void LapList::addLap(cpp3ds::Time actualTime)
{
	if (m_lapItems.empty())
		setEmptyListTextState(false);

	cpp3ds::Time oldTime;
	if (count() > 0)
		oldTime = m_lapItems.front().get()->getTime();

	std::shared_ptr<LapItem> item(new LapItem(m_lapItems.size() + 1, actualTime, oldTime));
	m_lapItems.insert(m_lapItems.begin(), std::move(item));

	repositionItems(false);
}

void LapList::clearList()
{
	m_lapItems.clear();

	repositionItems(true);
	setEmptyListTextState(true);
}

size_t LapList::count() const
{
	return m_lapItems.size();
}

void LapList::setEmptyListTextState(bool state)
{
	if (!state) {
		TweenEngine::Tween::to(m_textEmptyList, m_textEmptyList.SCALE_XY, 0.2f)
			.target(.8f, .8f)
			.start(m_tweenManager);

		TweenEngine::Tween::to(m_textEmptyList, m_textEmptyList.FILL_COLOR_ALPHA, 0.2f)
			.target(0)
			.start(m_tweenManager);
	} else {
		TweenEngine::Tween::to(m_textEmptyList, m_textEmptyList.SCALE_XY, 0.2f)
			.target(1.f, 1.f)
			.start(m_tweenManager);

		TweenEngine::Tween::to(m_textEmptyList, m_textEmptyList.FILL_COLOR_ALPHA, 0.2f)
			.target(255)
			.start(m_tweenManager);
	}
}

} // namespace Clock
